<template>
  <div class="main-content">
    <uploader
      :options="options"
      :file-status-text="fileStatusText"
      :autoStart="false"
      @file-added="onFileAdded"
      @file-success="onFileSuccess"
      @file-progress="onFileProgress"
      class="uploader-example"
    >
      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <p>将文件拖拽此处或者删除</p>
        <uploader-btn style="background-color: #67c13b;border-radius: 3px;"
          ><i class="el-icon-upload" style="margin-right: 5px"></i
          >上传文件</uploader-btn
        >
        <!-- <uploader-btn :attrs="attrs">select images</uploader-btn> -->
        <uploader-btn :directory="true" style="background-color: #79bbff;border-radius: 3px;"
          ><i class="el-icon-folder-add" style="margin-right: 5px"></i
          >上传文件夹</uploader-btn
        >
      </uploader-drop>
      <uploader-list></uploader-list>
    </uploader>
  </div>
</template>

<script>
import { merge } from "@/app/api/upload";
import SparkMD5 from "spark-md5";

export default {
  name: "uploadImg",
  data() {
    return {
      baseurl:api_url,
      options: {
        target: api_url+"api/upload/upload",
        testChunks: true,
        chunkSize: 1024 * 1024 * 1, //2MB
        simultaneousUploads: 1, //并发上传数
        headers: {},
        parseTimeRemaining: function (timeRemaining, parsedTimeRemaining) {
          //格式化时间
          return parsedTimeRemaining
            .replace(/\syears?/, "年")
            .replace(/\days?/, "天")
            .replace(/\shours?/, "小时")
            .replace(/\sminutes?/, "分钟")
            .replace(/\sseconds?/, "秒");
        },
        // 服务器分片校验函数
        checkChunkUploadedByResponse: (chunk, message) => {
          let obj = JSON.parse(message);
          let data = JSON.parse(obj.data);

          if (data.isExist) {
            // this.statusText.success = '秒传文件';
            return true;
          }
          return (data.uploaded || []).indexOf(chunk.offset + 1) >= 0;
        },
      },
      statusText: {
        success: "上传成功",
        error: "上传失败",
        uploading: "上传中",
        paused: "暂停中",
        waiting: "等待中",
        cmd5: "计算md5...",
      },
      attrs: {
        accept: "image/*",
      },
      fileStatusText: (status, response) => {
        return this.statusText[status];
      },
    };
  },
  methods: {
    onFileSuccess(rootFile, file, response, chunk) {
      let resp = JSON.parse(response);
      let data = JSON.parse(resp.data);
      if (data.merge === true) {
        merge({
          filename: file.name,
          identifier: file.uniqueIdentifier,
          totalSize: file.size,
          totalChunks: chunk.offset + 1,
        }).then((res) => {
          console.log(res);
        });
      } else {
        console.log("上传成功，不需要合并");
      }
    },
    onFileAdded(file) {
      // 计算MD5
      this.computeMD5(file);
    },
    //计算MD5
    computeMD5(file) {
      let blobSlice =
          File.prototype.slice ||
          File.prototype.mozSlice ||
          File.prototype.webkitSlice,
        chunkSize = 1024 * 1024 * 1,
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();
      let time = new Date().getTime();
      // console.log('计算MD5...')
      file.cmd5 = true;

      fileReader.onload = (e) => {
        spark.append(e.target.result); // Append array buffer
        currentChunk++;

        if (currentChunk < chunks) {
          console.log(
            `第${currentChunk}分片解析完成, 开始第${
              currentChunk + 1
            } / ${chunks}分片解析`
          );
          // let percent = Math.floor(currentChunk / chunks * 100);
          // console.log(percent);
          // file.cmd5progress = percent;
          loadNext();
        } else {
          console.log("finished loading");
          let md5 = spark.end();
          console.log(
            `MD5计算完成：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${
              file.size
            } 用时：${new Date().getTime() - time} ms`
          );
          spark.destroy(); //释放缓存
          file.uniqueIdentifier = md5; //将文件md5赋值给文件唯一标识
          file.cmd5 = false; //取消计算md5状态
          file.resume(); //开始上传
          // console.log(file);
        }
      };
      fileReader.onerror = () => {
        console.warn("oops, something went wrong.");
        file.cancel();
      };
      let loadNext = () => {
        let start = currentChunk * chunkSize,
          end = start + chunkSize >= file.size ? file.size : start + chunkSize;

        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
      };

      loadNext();
    },
    // 文件进度的回调
    onFileProgress(rootFile, file, chunk) {
      console.log(
        `上传中 ${file.name}，chunk：${chunk.startByte / 1024 / 1024} ~ ${
          chunk.endByte / 1024 / 1024
        }`
      );
    },
  },
};
</script>

<style>
.uploader-example {
  width: 90%;
  padding: 15px;
  margin: 0 auto 0;
  font-size: 14px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
}
.uploader-example .uploader-btn {
  margin-right: 8px;
  color: #ffffff;
  border: #ffffff;
}
.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
.uploader-file-icon[icon="image"]:before {
  content: "" !important;
  background: url("./icon/img.png") no-repeat;
  background-size: 24px 24px;
}

.uploader-file-icon[icon="folder"]::before {
  content: "" !important;
  background: url("./icon/folder.png") no-repeat;
  background-size: 24px 24px;
}
.uploader-file-icon[icon="video"]::before {
  content: "" !important;
  background: url("./icon/video.png") no-repeat;
  background-size: 24px 24px;
}
.uploader-file-icon[icon="audio"]::before {
  content: "" !important;
  background: url("./icon/audio.png") no-repeat;
  background-size: 24px 24px;
}
.uploader-file-icon[icon="document"]::before {
  content: "" !important;
  background: url("./icon/document.png") no-repeat;
  background-size: 24px 24px;
}
</style>
